<template>
  <div class="supplychain-container">
    <h1>供应链管理</h1>
    
    <div class="tabs">
      <button 
        :class="{ active: activeTab === 'suppliers' }" 
        @click="activeTab = 'suppliers'"
      >
        供应商管理
      </button>
      <button 
        :class="{ active: activeTab === 'purchase-orders' }" 
        @click="activeTab = 'purchase-orders'"
      >
        采购订单
      </button>
      <button 
        :class="{ active: activeTab === 'inventory' }" 
        @click="activeTab = 'inventory'"
      >
        库存管理
      </button>
    </div>
    
    <!-- 供应商管理 -->
    <div v-if="activeTab === 'suppliers'" class="tab-content">
      <div class="toolbar">
        <button @click="showAddSupplierModal = true" class="btn-primary">
          新增供应商
        </button>
      </div>
      
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>编码</th>
              <th>名称</th>
              <th>联系人</th>
              <th>电话</th>
              <th>地址</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="supplier in suppliers" :key="supplier.id">
              <td>{{ supplier.code }}</td>
              <td>{{ supplier.name }}</td>
              <td>{{ supplier.contact_person }}</td>
              <td>{{ supplier.phone }}</td>
              <td>{{ supplier.address }}</td>
              <td>{{ supplier.status }}</td>
              <td>
                <button @click="editSupplier(supplier)" class="btn-edit">编辑</button>
                <button @click="deleteSupplier(supplier.id)" class="btn-delete">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 采购订单 -->
    <div v-if="activeTab === 'purchase-orders'" class="tab-content">
      <div class="toolbar">
        <button @click="showAddPurchaseOrderModal = true" class="btn-primary">
          新增采购订单
        </button>
      </div>
      
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>供应商</th>
              <th>订单日期</th>
              <th>总金额</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in purchaseOrders" :key="order.id">
              <td>{{ order.order_no }}</td>
              <td>{{ getSupplierName(order.supplier_id) }}</td>
              <td>{{ order.order_date }}</td>
              <td>{{ order.total_amount }}</td>
              <td>{{ order.status }}</td>
              <td>
                <button @click="editPurchaseOrder(order)" class="btn-edit">编辑</button>
                <button @click="deletePurchaseOrder(order.id)" class="btn-delete">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 库存管理 -->
    <div v-if="activeTab === 'inventory'" class="tab-content">
      <div class="toolbar">
        <button @click="refreshInventory" class="btn-primary">
          刷新库存
        </button>
      </div>
      
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>产品编码</th>
              <th>产品名称</th>
              <th>当前库存</th>
              <th>安全库存</th>
              <th>单位</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in inventory" :key="item.id">
              <td>{{ item.product_code }}</td>
              <td>{{ item.product_name }}</td>
              <td>{{ item.current_stock }}</td>
              <td>{{ item.safety_stock }}</td>
              <td>{{ item.unit }}</td>
              <td>{{ item.status }}</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    
    <!-- 新增/编辑供应商模态框 -->
    <div v-if="showAddSupplierModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="showAddSupplierModal = false">&times;</span>
        <h2>{{ editingSupplier ? '编辑供应商' : '新增供应商' }}</h2>
        <form @submit.prevent="saveSupplier">
          <div class="form-group">
            <label>编码:</label>
            <input v-model="supplierForm.code" type="text" required />
          </div>
          <div class="form-group">
            <label>名称:</label>
            <input v-model="supplierForm.name" type="text" required />
          </div>
          <div class="form-group">
            <label>联系人:</label>
            <input v-model="supplierForm.contact_person" type="text" />
          </div>
          <div class="form-group">
            <label>电话:</label>
            <input v-model="supplierForm.phone" type="text" />
          </div>
          <div class="form-group">
            <label>地址:</label>
            <input v-model="supplierForm.address" type="text" />
          </div>
          <div class="form-group">
            <label>状态:</label>
            <select v-model="supplierForm.status">
              <option value="ACTIVE">启用</option>
              <option value="INACTIVE">停用</option>
            </select>
          </div>
          <div class="form-actions">
            <button type="submit" class="btn-primary">保存</button>
            <button type="button" @click="showAddSupplierModal = false">取消</button>
          </div>
        </form>
      </div>
    </div>
    
    <!-- 新增/编辑采购订单模态框 -->
    <div v-if="showAddPurchaseOrderModal" class="modal">
      <div class="modal-content">
        <span class="close" @click="showAddPurchaseOrderModal = false">&times;</span>
        <h2>{{ editingPurchaseOrder ? '编辑采购订单' : '新增采购订单' }}</h2>
        <form @submit.prevent="savePurchaseOrder">
          <div class="form-group">
            <label>订单号:</label>
            <input v-model="purchaseOrderForm.order_no" type="text" required />
          </div>
          <div class="form-group">
            <label>供应商:</label>
            <select v-model="purchaseOrderForm.supplier_id" required>
              <option value="">请选择供应商</option>
              <option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id">
                {{ supplier.name }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>订单日期:</label>
            <input v-model="purchaseOrderForm.order_date" type="date" required />
          </div>
          <div class="form-group">
            <label>状态:</label>
            <select v-model="purchaseOrderForm.status">
              <option value="DRAFT">草稿</option>
              <option value="APPROVED">已批准</option>
              <option value="COMPLETED">已完成</option>
              <option value="CANCELLED">已取消</option>
            </select>
          </div>
          <div class="form-actions">
            <button type="submit" class="btn-primary">保存</button>
            <button type="button" @click="showAddPurchaseOrderModal = false">取消</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useSupplyChainStore } from '@/stores/supplychain'

export default {
  name: 'SupplyChain',
  setup() {
    const supplyChainStore = useSupplyChainStore()
    
    const activeTab = ref('suppliers')
    const showAddSupplierModal = ref(false)
    const showAddPurchaseOrderModal = ref(false)
    const editingSupplier = ref(null)
    const editingPurchaseOrder = ref(null)
    
    const suppliers = ref([])
    const purchaseOrders = ref([])
    const inventory = ref([])
    
    const supplierForm = reactive({
      code: '',
      name: '',
      contact_person: '',
      phone: '',
      address: '',
      status: 'ACTIVE'
    })
    
    const purchaseOrderForm = reactive({
      order_no: '',
      supplier_id: '',
      order_date: '',
      status: 'DRAFT'
    })
    
    // 获取供应商列表
    const fetchSuppliers = async () => {
      try {
        // 这里应该调用实际的API
        suppliers.value = [
          {
            id: 1,
            code: 'SUP001',
            name: 'ABC供应商',
            contact_person: '张三',
            phone: '13800138000',
            address: '北京市朝阳区xxx街道',
            status: 'ACTIVE'
          }
        ]
      } catch (error) {
        console.error('获取供应商列表失败:', error)
      }
    }
    
    // 获取采购订单列表
    const fetchPurchaseOrders = async () => {
      try {
        // 这里应该调用实际的API
        purchaseOrders.value = [
          {
            id: 1,
            order_no: 'PO2023001',
            supplier_id: 1,
            order_date: '2023-01-15',
            total_amount: 50000,
            status: 'APPROVED'
          }
        ]
      } catch (error) {
        console.error('获取采购订单列表失败:', error)
      }
    }
    
    // 获取库存信息
    const fetchInventory = async () => {
      try {
        // 这里应该调用实际的API
        inventory.value = [
          {
            id: 1,
            product_code: 'PRD001',
            product_name: '产品A',
            current_stock: 100,
            safety_stock: 20,
            unit: '件',
            status: 'NORMAL'
          }
        ]
      } catch (error) {
        console.error('获取库存信息失败:', error)
      }
    }
    
    // 根据供应商ID获取供应商名称
    const getSupplierName = (supplierId) => {
      const supplier = suppliers.value.find(s => s.id === supplierId)
      return supplier ? supplier.name : ''
    }
    
    // 编辑供应商
    const editSupplier = (supplier) => {
      editingSupplier.value = supplier
      Object.assign(supplierForm, supplier)
      showAddSupplierModal.value = true
    }
    
    // 删除供应商
    const deleteSupplier = (id) => {
      if (confirm('确定要删除这个供应商吗？')) {
        // 这里应该调用实际的API
        suppliers.value = suppliers.value.filter(s => s.id !== id)
      }
    }
    
    // 保存供应商
    const saveSupplier = () => {
      if (editingSupplier.value) {
        // 编辑供应商
        const index = suppliers.value.findIndex(s => s.id === editingSupplier.value.id)
        if (index !== -1) {
          suppliers.value[index] = { ...supplierForm, id: editingSupplier.value.id }
        }
      } else {
        // 新增供应商
        const newSupplier = {
          ...supplierForm,
          id: Date.now() // 简单生成ID
        }
        suppliers.value.push(newSupplier)
      }
      
      // 重置表单和状态
      resetSupplierForm()
      showAddSupplierModal.value = false
    }
    
    // 重置供应商表单
    const resetSupplierForm = () => {
      Object.assign(supplierForm, {
        code: '',
        name: '',
        contact_person: '',
        phone: '',
        address: '',
        status: 'ACTIVE'
      })
      editingSupplier.value = null
    }
    
    // 编辑采购订单
    const editPurchaseOrder = (order) => {
      editingPurchaseOrder.value = order
      Object.assign(purchaseOrderForm, order)
      showAddPurchaseOrderModal.value = true
    }
    
    // 删除采购订单
    const deletePurchaseOrder = (id) => {
      if (confirm('确定要删除这个采购订单吗？')) {
        // 这里应该调用实际的API
        purchaseOrders.value = purchaseOrders.value.filter(o => o.id !== id)
      }
    }
    
    // 保存采购订单
    const savePurchaseOrder = () => {
      if (editingPurchaseOrder.value) {
        // 编辑采购订单
        const index = purchaseOrders.value.findIndex(o => o.id === editingPurchaseOrder.value.id)
        if (index !== -1) {
          purchaseOrders.value[index] = { ...purchaseOrderForm, id: editingPurchaseOrder.value.id }
        }
      } else {
        // 新增采购订单
        const newOrder = {
          ...purchaseOrderForm,
          id: Date.now(), // 简单生成ID
          total_amount: 0 // 默认金额为0
        }
        purchaseOrders.value.push(newOrder)
      }
      
      // 重置表单和状态
      resetPurchaseOrderForm()
      showAddPurchaseOrderModal.value = false
    }
    
    // 重置采购订单表单
    const resetPurchaseOrderForm = () => {
      Object.assign(purchaseOrderForm, {
        order_no: '',
        supplier_id: '',
        order_date: '',
        status: 'DRAFT'
      })
      editingPurchaseOrder.value = null
    }
    
    // 刷新库存
    const refreshInventory = () => {
      fetchInventory()
    }
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchSuppliers()
      fetchPurchaseOrders()
      fetchInventory()
    })
    
    return {
      activeTab,
      showAddSupplierModal,
      showAddPurchaseOrderModal,
      editingSupplier,
      editingPurchaseOrder,
      suppliers,
      purchaseOrders,
      inventory,
      supplierForm,
      purchaseOrderForm,
      fetchSuppliers,
      fetchPurchaseOrders,
      fetchInventory,
      getSupplierName,
      editSupplier,
      deleteSupplier,
      saveSupplier,
      editPurchaseOrder,
      deletePurchaseOrder,
      savePurchaseOrder,
      refreshInventory
    }
  }
}
</script>

<style scoped>
.supplychain-container {
  padding: 20px;
}

.tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #ddd;
}

.tabs button {
  padding: 10px 20px;
  background: none;
  border: none;
  cursor: pointer;
  border-bottom: 3px solid transparent;
}

.tabs button.active {
  border-bottom-color: #007bff;
  font-weight: bold;
}

.tab-content {
  padding: 20px 0;
}

.toolbar {
  margin-bottom: 20px;
}

.btn-primary {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-edit, .btn-delete {
  padding: 4px 8px;
  margin-right: 5px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.btn-edit {
  background-color: #ffc107;
  color: #212529;
}

.btn-delete {
  background-color: #dc3545;
  color: white;
}

.table-container {
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f8f9fa;
  font-weight: bold;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.modal {
  position: fixed;
  z-index: 1000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
  background-color: #fefefe;
  margin: 5% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
  max-width: 500px;
  position: relative;
}

.close {
  position: absolute;
  right: 15px;
  top: 15px;
  font-size: 28px;
  font-weight: bold;
  cursor: pointer;
}
</style>